package com.estronger.shopmanage.fragment.measure.pg;

import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.estronger.pull_to_refresh_expandablelist.CommonFooterView.State;
import com.estronger.pull_to_refresh_expandablelist.PullToRefreshBase;
import com.estronger.pull_to_refresh_expandablelist.PullToRefreshBase.OnRefreshListener;
import com.estronger.pull_to_refresh_expandablelist.PullToRefreshListView;
import com.estronger.shopmanage.R;
import com.estronger.shopmanage.adapter.tasking.TmsAdapter;
import com.estronger.shopmanage.base.MyApplication;
import com.estronger.shopmanage.bean.B101PgMeasureList;
import com.estronger.shopmanage.bean.B101PgMeasureList.Datas.PgMeasureListData;
import com.estronger.shopmanage.manager.NetManager;
import com.estronger.shopmanage.ui.order.until.Tools;
import com.estronger.shopmanage.ui.measure.pg.MeasurePGActivity;
import com.estronger.shopmanage.utils.JsonUtil;
import com.estronger.shopmanage.utils.NetUtils;
import com.estronger.shopmanage.utils.Toast;
import com.estronger.shopmanage.view.CircularProgress;
import com.google.gson.Gson;
import com.lidroid.xutils.http.RequestParams;

import java.util.ArrayList;

import cn.jesse.nativelogger.NLogger;

public abstract class MsPGBaseFragment extends Fragment implements
        OnRefreshListener<ListView> {

    protected PullToRefreshListView mListView;// 下拉刷新的ListView
    protected RequestParams params;
    protected RelativeLayout root;// 根View
    protected CircularProgress bar;// 进度条
    protected TextView empty_view;// 没数据是展示
    protected TmsAdapter adapter;// 适配器
    // 存放测量条目数据
    protected ArrayList<PgMeasureListData> data = new ArrayList<PgMeasureListData>();
    Gson gson = new Gson();
    private MeasurePGActivity activity;
    private String pagesize = "10";
    public static boolean isRestart = false;//当前Fragment或Activity是否是从被覆盖状态重新可见的情况？

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // return super.onCreateView(inflater, container, savedInstanceState);
        activity = (MeasurePGActivity) getActivity();
        root = (RelativeLayout) View.inflate(activity,
                R.layout.fragment_history, null);
        mListView = (PullToRefreshListView) root
                .findViewById(R.id.success_listview);

        bar = (CircularProgress) root.findViewById(R.id.loding_view);
        empty_view = (TextView) root.findViewById(R.id.empty_view);

        mListView.setOnRefreshListener(this);
        mListView.setState(State.HIDE);
        adapter = new TmsAdapter(activity, data, gson, gettype());
        mListView.setAdapter(adapter);

        return root;
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    protected abstract boolean needConnect();

    protected abstract String gettype();

    public void connect(final String type, final int pageNo) {
        if (activity != null) {
            activity.getTitleNum();
        }else{
            activity = (MeasurePGActivity) getActivity();
        }
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                params = new RequestParams();
                params.addBodyParameter("sf_action", "getassignlist");
                params.addBodyParameter("usercode", MyApplication.getUserCode());
                params.addBodyParameter("gettype", type);
                params.addBodyParameter("pagesize", pagesize);
                params.addBodyParameter("pageindex", pageNo+"");
                netManager.connectWork(params, NetManager.PG_MEASURE_LIST);
            }
        }, 1000);
    }

    protected NetManager netManager = new NetManager() {
        @Override
        public void onNetWorkErorr(int code, String result) {
            try {
                if (null != mListView) {
                    mListView.setState(State.HIDE);
                    if (null != bar)
                        bar.setVisibility(View.GONE);
                    mListView.onRefreshComplete();
                    if (data.size() == 0) {
                        empty_view.setVisibility(View.VISIBLE);
                    }
                }
            } catch (Exception e) {
                NLogger.e("" + e.getMessage());
            }
        }

        @Override
        public void onNetWorkSuccess(int code, String result) {
            if (null != bar)
                bar.setVisibility(View.GONE);
            if (null != mListView) {
                mListView.setState(State.HIDE);
                mListView.onRefreshComplete();
                if (code == NetManager.PG_MEASURE_LIST) {
                    B101PgMeasureList bean = gson.fromJson(result, B101PgMeasureList.class);
                    Tools.pmIndexMap.put(gettype(), bean.data.pageindex);
                    Tools.pmCountMap.put(gettype(), JsonUtil.getPageCount(10, bean.data.total));
                    if (Tools.pmIndexMap.get(gettype()) == 1) {
                        data.clear();
                        if (bean.data.list.size() >= Integer.parseInt(pagesize)) {
                            mListView.setMode(PullToRefreshBase.Mode.BOTH);
                        }
                    }
                    if (bean.success && bean.data != null && bean.data.total > 0) {
                        if (bean.data.list == null || bean.data.list.size() == 0) {
                            if (!isRestart) {
                                Toast.show(getActivity(), "没有更多了！", 1500);
                            }
                            return;
                        }
                        data.addAll(bean.data.list);
                        if (data.size() > 0
                                && empty_view.getVisibility() == View.VISIBLE) {
                            empty_view.setVisibility(View.GONE);
                        }
                        if (data.size() == 0) {
                            empty_view.setVisibility(View.VISIBLE);
                        }
                    } else {
                        empty_view.setVisibility(View.VISIBLE);
                    }
                    adapter.notifyDataSetChanged();
                    //mListView.setSelection((pageindex-1)*Integer.parseInt(pagesize)-3);
                }
            }
        }
    };

    protected void loadData(int pageNo) {
        if (!NetUtils.isNetworkConnected(activity)) {
            mListView.postDelayed(new Runnable() {
                @Override
                public void run() {
                    mListView.onRefreshComplete();
                    Toast.show(activity, "当前无网络链接！", 2000);
                }
            }, 1000);
        } else {
            connect(gettype(), pageNo);
        }
    }

    /**
     * 下拉刷新时调用
     */
    @Override
    public void onRefresh(PullToRefreshBase<ListView> refreshView) {
        isRestart = false;
        if (mListView.isHeaderShown()) {
            Tools.pmIndexMap.put(gettype(), 1);
            loadData(1);
        } else if (mListView.isFooterShown()) {
            if(Tools.pmIndexMap.get(gettype()) < Tools.pmCountMap.get(gettype())) {
                loadData(Tools.pmIndexMap.get(gettype()) + 1);
            }else {
                Toast.show(getContext(), "~没有更多啦~", Toast.LENGTH_SHORT);
            }
        }
        mListView.postDelayed(new Runnable() {
            @Override
            public void run() {
                mListView.onRefreshComplete();
            }
        }, 1000);
    }
}
